package data.join.com.media;

import android.content.Context;
import android.text.TextUtils;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import data.join.com.carapi.ApiPref;
import data.join.com.carapi.PhotoResult;
import data.join.com.database.bean.PhotoBean;
import data.join.com.database.bean.PhotoPref;
import data.join.com.network.RetrofitManager;
import data.join.com.network.gson.UpdateCommandRequest;
import data.join.com.service.MainService;
import data.join.com.utils.BaseThread;
import data.join.com.utils.MyLog;
import data.join.com.utils.QiniuApi;
import data.join.com.utils.WakeLockUtils;
import retrofit2.Call;

/**
 * Created by Administrator on 2017/11/23.
 */

public class PhotoHandleThread extends BaseThread {

    private static final String TAG = PhotoHandleThread.class.getSimpleName();

    private static PhotoHandleThread mInstance;

    private Context mContext;

    private PhotoHandleThread(Context context){
        this.mContext = context;
    }

    public static PhotoHandleThread getInstance(Context context){
        if(mInstance == null){
            mInstance = new PhotoHandleThread(context);
        }
        return mInstance;
    }

    @Override
    public void run() {
        while (true){
            if(MainService.isNetWorkConnect(mContext,TAG)) {
                WakeLockUtils.getDefault(mContext).acquireWakeLock(TAG);
                handlePhotoCommand();
                WakeLockUtils.getDefault(mContext).releaseWakeLock(TAG);
            }
            await(TIME_WAIT);
        }
    }

    private void handlePhotoCommand(){

        while (true){
            PhotoBean photoBean = PhotoPref.getInstance().getLastUnHandleCommand();

            if(photoBean == null){
                MyLog.D(TAG, "photoBean is NULL,no photoBean need handle,break");
                break;
            }else {
                if(!doHandle(photoBean)){
                    break;
                }
            }
        }
    }

    private boolean doHandle(PhotoBean photoBean){
        boolean ret = false;

        if(TextUtils.isEmpty(photoBean.error)){
            PhotoResult photoResult = ApiPref.getInstance(mContext).takePhoto();

            if(photoResult != null && photoResult.isAvail()){
                HandleHelp handleHelp = uploadFile(photoResult);
                if(handleHelp.cloudKeyAvail()){
                    handleHelp.photoResult = photoResult;
                    if(sendCommandResult(photoBean,handleHelp)){
                        MyLog.D(TAG,"sendCommandResult take photo success");
                        photoDoSave(photoBean);
                    }else{
                        photoBean.error = "report fail";
                        PhotoPref.getInstance().updatePhotoBean(photoBean);
                    }
                }else{
                    photoBean.error = "upload photo fail";
                    PhotoPref.getInstance().updatePhotoBean(photoBean);
                }
            }else{
                photoBean.error = "take photo fail";
                PhotoPref.getInstance().updatePhotoBean(photoBean);
            }
        }

        if(TextUtils.isEmpty(photoBean.error)){

        }else{
            if(sendCommandResult(photoBean,null)){
                photoDoSave(photoBean);
            }else{
                MyLog.D(TAG,"sendCommandResult fail,photoBean.error="+photoBean.error);
            }
        }

        return ret;
    }

    private void photoDoSave(PhotoBean photoBean){
        photoBean.handleState = PhotoPref.HANDLE_STATE_HANDLED;
        PhotoPref.getInstance().updatePhotoBean(photoBean);
        MyLog.D(TAG,"photoDoSave");
    }

    private HandleHelp uploadFile(PhotoResult photoResult){

        HandleHelp handleHelp = new HandleHelp();

        if(photoResult.isAvailFront()){
           QiniuApi.UploadResult uploadResult = QiniuApi.getDefault().startUploadAsync(photoResult.imgurl,QiniuApi.getQiniuLogToken(photoResult.imgurl));
           if(uploadResult != null){
               handleHelp.keyFront = uploadResult.cloudKey;
           }
        }

        if(photoResult.isAvailBack()){
            QiniuApi.UploadResult uploadResult = QiniuApi.getDefault().startUploadAsync(photoResult.imgurlrear,QiniuApi.getQiniuLogToken(photoResult.imgurlrear));
            if(uploadResult != null){
                handleHelp.keyBack = uploadResult.cloudKey;
            }
        }

        return handleHelp;
    }

    private boolean sendCommandResult(PhotoBean photoBean,HandleHelp handleHelp){
        boolean ret = false;

        UpdateCommandRequest commandRequest = new UpdateCommandRequest();
        HashMap<String,String> content = new HashMap<>();

        if(handleHelp != null) {
            content.put("photo_key_front", handleHelp.keyFront);
            content.put("photo_key_back", handleHelp.keyBack);
            content.put("fsize_front", handleHelp.getFrontSize());
            content.put("fsize_back", handleHelp.getBackSize());
        }

        content.put("command_type",photoBean.type);

        commandRequest.content = content;
        commandRequest.error = photoBean.error;

        Call<Object> objectCall = RetrofitManager.getApiService().updateCommand(photoBean.commandId,RetrofitManager.getBodyByJson(commandRequest));

        try {
            ret = objectCall.execute().isSuccessful();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if(!ret){
            MyLog.E(TAG,"sendCommandResult first time fail,retry after 3 second!");
            await(3);
            objectCall = RetrofitManager.getApiService().updateCommand(photoBean.commandId,RetrofitManager.getBodyByJson(commandRequest));
            try {
                ret = objectCall.execute().isSuccessful();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return ret;
    }


    private class HandleHelp{
        PhotoResult photoResult;

        String keyFront;
        String keyBack;

        public boolean cloudKeyAvail(){
            boolean ret = true;

            if(TextUtils.isEmpty(keyFront) && TextUtils.isEmpty(keyBack)){
                ret = false;
            }

            return ret;
        }

        public String getFrontSize(){
            String size = null;
            if(photoResult.isAvailFront()){
                File file =  new File(photoResult.imgurl);
                if(file.exists()){
                    size = Long.toString(file.length());
                }else{
                    size ="0";
                }
            }
            return size;
        }
        public String getBackSize(){
            String size = null;
            if(photoResult.isAvailBack()){
                File file =  new File(photoResult.imgurlrear);
                if(file.exists()){
                    size = Long.toString(file.length());
                }else{
                    size ="0";
                }
            }
            return size;
        }
    }
}
